package com.longxi.tianjintianbao.ui.presenter.goodstraffic;

import android.content.Intent;
import android.view.View;
import android.widget.EditText;

import com.longxi.tianjintianbao.AppConst;
import com.longxi.tianjintianbao.MyApplication;
import com.longxi.tianjintianbao.R;
import com.longxi.tianjintianbao.api.ApiRetrofit;
import com.longxi.tianjintianbao.api.response.BaseResponse;
import com.longxi.tianjintianbao.api.response.HttpResult;
import com.longxi.tianjintianbao.exception.ExceptionHandle;
import com.longxi.tianjintianbao.exception.MySubscriber;
import com.longxi.tianjintianbao.model.GoodsTraffic;
import com.longxi.tianjintianbao.ui.activity.repair_publish.SelectAreaActivity;
import com.longxi.tianjintianbao.ui.base.BaseActivity;
import com.longxi.tianjintianbao.ui.base.BasePresenter;
import com.longxi.tianjintianbao.ui.presenter.repair_publish.SelectAreaAtPresenter;
import com.longxi.tianjintianbao.ui.view.goodstraffic.ISignGoodsTrafficAtView;
import com.longxi.tianjintianbao.utils.MyUtils;
import com.longxi.tianjintianbao.utils.NListRefresh;

import org.json.JSONException;
import org.json.JSONObject;

import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class SignGoodsTrafficAtPresenter extends BasePresenter<ISignGoodsTrafficAtView> {

    private String houseid = "";
    private GoodsTraffic goodsTraffic = null;
    private String billid = "";
    private String state;

    public SignGoodsTrafficAtPresenter(BaseActivity context) {
        super(context);
    }

    public void setBar() {
        Intent intent = mContext.getIntent();
//        goodsTraffic = (GoodsTraffic) intent.getSerializableExtra(AppConst.GOODSTRAFFIC);
        billid = intent.getStringExtra(AppConst.BILLID);
        state = intent.getStringExtra(AppConst.STATE);
        mContext.setTitle("物品放行");
        mContext.setTvLeft(MyUtils.getString(R.string.back));

        if(billid == null || billid == ""){
            initInputSelectBoxView();
            return;
        }
        mContext.setTitle("物品放行详情");
        if("0".equals(state)){
            getView().getBtnLogin().setText("物品放行离开登记");
        }else{
            getView().getBtnLogin().setVisibility(View.GONE);
        }
        getDetail();
    }

    private void getDetail(){
        mContext.showWaitingDialog(MyUtils.getString(R.string.load));
        JSONObject object = new JSONObject();
        try {
            object.put("billid", billid);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiRetrofit.getInstance().getGoodsRelease(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<HttpResult<GoodsTraffic>>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(HttpResult<GoodsTraffic> result) {
                mContext.hideWaitingDialog();
                if(result.getCode() != 0){
                    MyUtils.showToast(result.getMsg());
                    return;
                }
                goodsTraffic = result.getData().get(0);
                if(goodsTraffic == null){
                    MyUtils.showToast(MyUtils.getString(R.string.data_error));
                    return;
                }

                setDetail();
            }
        });
    }

    /**
     * 列表跳转过来 显示内容
     */
    private void setDetail() {
        getView().getRealname().setValue(R.mipmap.ic_release_realname, "无申请人真实姓名", goodsTraffic.getApplicant());
        getView().getPhone().setValue(R.mipmap.ic_release_phone, "无申请人联系方式", goodsTraffic.getPhone());
        getView().getHouse().setValue(R.mipmap.ic_release_house, "无申请人家庭住址", MyUtils.accordDiagonalSwitchString(goodsTraffic.getHouse()));
        getView().getGoods().setValue(R.mipmap.ic_release_goods, "无携出物品", goodsTraffic.getReleasegoods());
        getView().getTime().setValue(R.mipmap.ic_release_calendar, "无携出时间", goodsTraffic.getReleasetime());
        getView().getRemark().setValue(R.mipmap.ic_release_remark, "无备注", goodsTraffic.getExplain());
    }

    /**
     * 初始化输入框
     */
    public void initInputSelectBoxView() {
        getView().getRealname().setDate(R.mipmap.ic_release_realname, "请输入申请人真实姓名");
        getView().getPhone().setDate(R.mipmap.ic_release_phone, "请输入申请人联系方式");
        getView().getHouse().setDate(R.mipmap.ic_release_house, "请选择申请人家庭住址", true);
        getView().getGoods().setDate(R.mipmap.ic_release_goods, "请输入携出物品");
        getView().getTime().setDate(R.mipmap.ic_release_calendar, "请选择携出时间", true);
        getView().getRemark().setDate(R.mipmap.ic_release_remark, "备注: 您最多可输入200字", 200, 200);

        getView().getHouse().getEtValue().setOnClickListener(v -> selectArea());
        getView().getTime().getEtValue().setOnClickListener(v -> getCurrentDateTime(getView().getTime(), true));
    }

    public void btnLogin(){
        if(goodsTraffic == null){
            saveVisitor();
        }else{
            saveVisitorLeave();
        }
    }

    public void saveVisitor() {
        long userid = MyApplication.loginUser.userid;
        String applicant = getView().getRealname().getText();
        String phone = getView().getPhone().getText();
        String releasegoods = getView().getGoods().getText();
        String explain = getView().getRemark().getText();
        String releasetime = getView().getTime().getText();

        if("".equals(houseid) || houseid == null){
            MyUtils.showToast("请选择拜访房间");
            return;
        }

        if("".equals(phone) || phone == null){
            MyUtils.showToast("请输入申请人手机");
            return;
        }

        if("".equals(applicant) || applicant == null){
            MyUtils.showToast("请输入申请人");
            return;
        }

        if("".equals(releasegoods) || releasegoods == null){
            MyUtils.showToast("请输入携出物品");
            return;
        }

        if("".equals(explain) || explain == null){
            MyUtils.showToast("请输入说明");
            return;
        }

        if("".equals(releasetime) || releasetime == null){
            MyUtils.showToast("请选携出时间");
            return;
        }

        mContext.showWaitingDialog(MyUtils.getString(R.string.load));
        JSONObject object = new JSONObject();
        try {
            object.put("userid", userid);
            object.put("houseid", houseid);
            object.put("applicant", applicant);
            object.put("phone", phone);
            object.put("releasegoods", releasegoods);
            object.put("explain", explain);
            object.put("releasetime", releasetime);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiRetrofit.getInstance().saveGoodsRelease(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<BaseResponse>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                mContext.hideWaitingDialog();
                if(baseResponse.getCode() != 0){
                    MyUtils.showToast(baseResponse.getMsg());
                    return;
                }
                MyUtils.showToast("提交成功");
                mContext.setResult(mContext.RESULT_OK);
                mContext.finish();
            }
        });
    }

    private void saveVisitorLeave() {
        mContext.showWaitingDialog(MyUtils.getString(R.string.load));
        JSONObject object = new JSONObject();
        try {
            object.put("userid", MyApplication.loginUser.userid);
            object.put("billid", goodsTraffic.getBillid());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        ApiRetrofit.getInstance().saveGoodsLeave(object)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new MySubscriber<BaseResponse>(mContext) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable throwable) {
                mContext.hideWaitingDialog();
                MyUtils.showToast(throwable.message);
            }

            @Override
            public void onNext(BaseResponse baseResponse) {
                mContext.hideWaitingDialog();
                if(baseResponse.getCode() != 0){
                    MyUtils.showToast(baseResponse.getMsg());
                    return;
                }
                MyUtils.showToast("提交成功");
                mContext.setResult(mContext.RESULT_OK);
                mContext.finish();
            }
        });
    }

    /**
     * 选择小区地址
     */
    public void selectArea() {
        Intent mainIntent = new Intent(mContext, SelectAreaActivity.class);
        mainIntent.putExtra(SelectAreaAtPresenter.REPAIRAREA,"0");
        mContext.startActivityForResult(mainIntent, AppConst.IntentRequstCode.ACTIVITY_REPAIR_CONTENT);
    }

    public String getEditText(EditText editText){
        return editText.getText().toString().trim();
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == AppConst.IntentRequstCode.ACTIVITY_REPAIR_CONTENT) {
            if(data != null){
                houseid = data.getStringExtra("buildId");
                getView().getHouse().setText(data.getStringExtra("area") + data.getStringExtra("address"));
                if(getView().getRealname().getText() == null || "".equals(getView().getRealname().getText())){
                    getView().getRealname().setText(data.getStringExtra("custname"));
                    return;
                }
            }
        }
    }

}
